<template>
  <el-dialog v-model="isOpen" title="Tips" width="1000" :before-close="handleClose">
    <el-tabs v-model="activeName" v-if="isOpenCode" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane
        v-for="(item, index) in codeJson"
        :label="item.path.split('/').pop()"
        :key="index"
        :name="item.path.split('/').pop()"
      >
        <span>文件路径：<el-input v-model="item.path" /></span>
        <WangEditorView v-model:codeJson="item.html" v-model:codeJsonText="item.code" />
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        是否覆盖：<el-switch style="margin-right: 10px" size="small" v-model="cover" />
        <el-button
          @click="
            () => {
              isOpen = false
              isOpenCode = false
            }
          "
          >Cancel</el-button
        >
        <el-button type="primary" @click="genCode"> 生成代码 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, defineModel, defineProps, computed, inject, onBeforeMount } from 'vue'
import WangEditorView from '@/views/template/dataSource/CodeWangEditorView.vue'
import { ElMessage } from 'element-plus'
const api = inject('api')
const requestApi = api.getApi('FaSysGen', null)
const isOpen = defineModel('isOpen')
const props = defineProps(['genId'])
const genId = computed(() => props.genId)
const codeJson = ref([])
const isOpenCode = ref(false)
const cover = ref(false)
// 活跃标签
const activeName = ref('')

function handleClick(tab, event) {
  // console.log(tab, event)
}
onBeforeMount(() => {
  getCodepreView(genId.value)
})
// 获取预览代码
function getCodepreView(genId) {
  requestApi
    .genCodePreview(genId)
    .then((res) => {
      codeJson.value = JSON.parse(res.data)
      codeJson.value.forEach((item) => {
        item.html = `<pre><code class="language-java">${item.code.replaceAll('>', '&gt;').replaceAll('<', '&lt;')}</code></pre>`
      })
      activeName.value = codeJson.value[0].path.split('/').pop()
      isOpenCode.value = true
    })
    .catch((err) => {
      console.log(err)
    })
}
// 代码提取文本内容
function genCodeJsonHandle() {
  return JSON.stringify(codeJson.value)
}

// 生成代码
function genCode() {
  requestApi
    .genCode({ genId: genId.value, cover: cover.value, codeJsonStr: genCodeJsonHandle() })
    .then((res) => {
      ElMessage({ message: '代码生成成功!', type: 'success' })
    })
    .catch((err) => {
      console.error(err)
    })
}
// 叉掉弹出框
function handleClose(done) {
  done()
}
</script>
<style scoped></style>
